<template>
  <view class="upload-wrap">
    <up-upload
      :file-list="list"
      name="1"
      :accept="accept"
      :max-count="maxCount"
      :preview-full-image="previewFullImage"
      multiple
      :width="109"
      :height="109"
      @after-read="afterRead"
      @delete="deletePic"
    >
      <slot />
    </up-upload>
  </view>
</template>

<script lang="ts" setup>
export interface FILE {
  size: number;
  type: string;
  url: string;
  status?: string;
  message?: string;
  [propName: string]: any;
}

const props = defineProps({
  list: {
    type: Array<FILE>,
    default: () => [],
  },

  accept: {
    type: String,
    default: 'media',
  },

  maxCount: {
    type: [String, Number],
    default: 52,
  },

  previewFullImage: {
    type: Boolean,
    default: true,
  },
});

const emits = defineEmits(['update:list']);

// 上传方法
// const uploadFilePromise = (url: string): Promise<string> => {
//   return new Promise((resolve) => {
//     uni.uploadFile({
//       url: 'http://192.168.2.21:7001/upload', // 仅为示例，非真实的接口地址
//       filePath: url,
//       name: 'file',
//       formData: {
//         user: 'test',
//       },
//       success: (res: any) => {
//         setTimeout(() => {
//           resolve(res.data.data);
//         }, 1000);
//       },
//     });
//   });
// };

// 新增图片
const afterRead = async ({ file }: { file: Array<FILE> }) => {
  console.log('event=======2', file);
  // 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
  const lists: Array<FILE> = [...file];
  const fileList: Array<FILE> = props.list;
  // let fileListLen = props.list.length;
  lists.forEach((item: FILE) => {
    fileList.push({
      ...item,
      status: 'success',
      message: '',
    });
  });
  emits('update:list', fileList);
  // for (let i = 0; i < lists.length; i++) {
  //   const result: string = await uploadFilePromise(lists[i].url);
  //   const item: FILE = props.list[fileListLen];
  //   fileList.splice(fileListLen, 1, {
  //     ...item,
  //     status: 'success',
  //     message: '',
  //     url: result,
  //   });
  //   emits('update:list', fileList);
  //   fileListLen++;
  // }
};

// 删除图片
const deletePic = ({ index }: { index: number }) => {
  const fileList = props.list;
  fileList.splice(index, 1);
  emits('update:list', fileList);
};
</script>
